# coding=utf-8
import logging
import json
import requests

from common.bank_record.db import get_max_cash_flow_by_card_name
from common.bankcard.model import BankCard, BANKCARD_TYPE
from common.utils.alipay_trans_to_bank import get_alipay_trans_bankcard_url
from common.utils.telegram import send
from common.bankcard import db as bankcard_db
from common.utils import exceptions as err

_LOGGER = logging.getLogger('hydra')


def get_bankcard_pay_url(bankcard_id, amount=None):
    bankcard = BankCard.query.filter(BankCard.id == bankcard_id).first()
    if bankcard is None:
        return None
    return get_alipay_trans_bankcard_url(bankcard.account_number,
                                         bankcard.account_holder,
                                         bankcard.bank, amount)


_SMS_VCODE_URL = 'http://103.230.242.129:23456/smscat/api/get_last_sms_verify_info/?phone={}&time={}'


def get_sms_vcode(card_name, click_time):
    bankcard = BankCard.query.filter(BankCard.name == card_name).first()
    if bankcard is None or bankcard.phone is None:
        return None
    reponse = requests.get(_SMS_VCODE_URL.format(bankcard.phone, click_time)).text
    return json.loads(reponse)['data']['vcode']


def card_balance_alert(card_id, host):
    card = bankcard_db.get_bankcard(card_id)
    if not card:
        raise err.ResourceNotFound('card_id ' + str(card_id) +
                                   ' cannot be found')

    if card.type == BANKCARD_TYPE.PAYMENT and \
            card.balance <= card.min_balance_limit:
        __card_min_balance_alert(card, host)

    if card.type == BANKCARD_TYPE.RECHARGE and \
            card.balance >= card.max_balance_limit:
        __card_max_balance_alert(card, host)

    today_cash_flow_alert(card, host)


def today_cash_flow_alert(card, host):
    today_cash_flow = get_max_cash_flow_by_card_name(card.name)
    if today_cash_flow >= card.max_cash_flow:
        bankcard_db.inactive_bankcard_status_by_card_name(card.name)
        __card_max_cash_flow_alert(card, host, today_cash_flow)


def __card_min_balance_alert(card, host):
    telegram_header = "Balance Min Limit Reached"
    message = "Bank: " + (card.bank_en or card.bank) + "\r\n" + \
        " Card Code: " + card.name + "\r\n" + \
        " Username: " + unicode(card.account_holder) + "\r\n" + \
        " Account No: " + hide_account_number(card.account_number) + "\r\n" + \
        " Min Balance Limit: " + str(card.min_balance_limit) + "\r\n" + \
        " Available Balance: " + str(card.balance or 0)
    message = "*" + telegram_header + "* \r\n``` " + message + " ```"
    send(message, host, card.type)


def __card_max_balance_alert(card, host):
    telegram_header = "Balance Max Limit Reached"
    message = "Bank: " + (card.bank_en or card.bank) + "\r\n" + \
        " Card Code: " + card.name + "\r\n" + \
        " Username: " + unicode(card.account_holder) + "\r\n" + \
        " Account No: " + hide_account_number(card.account_number) + "\r\n" + \
        " Max Balance Limit: " + str(card.max_balance_limit) + "\r\n" + \
        " Available Balance: " + str(card.balance or 0)
    message = "*" + telegram_header + "* \r\n``` " + message + " ```"
    send(message, host, card.type)


def __card_max_cash_flow_alert(card, host, today_cash_flow):
    telegram_header = u"Cash Flow Max Limit Reached，Has been automatically closed"
    message = "Bank: " + (card.bank_en or card.bank) + "\r\n" + \
        " Card Code: " + card.name + "\r\n" + \
        " Username: " + unicode(card.account_holder) + "\r\n" + \
        " Account No: " + hide_account_number(card.account_number) + "\r\n" + \
        " Max Cash Flow Limit: " + str(card.max_cash_flow) + "\r\n" + \
        " Available Today's Cash Flow: " + str(today_cash_flow or 0)
    message = "*" + telegram_header + "* \r\n``` " + message + " ```"
    send(message, host, card.type)


def hide_account_number(data):
    if not data:
        return ''

    data = data.replace(" ", "")
    start_len, end_len = (3, 4)
    start, padding, end = (data, "", "")

    if len(data) >= start_len:
        start = data[0:start_len]
        end = data[start_len:]
        if len(data[start_len:]) >= end_len:
            end = data[start_len:][-end_len:]
            padding = "*" * (len(data) - (start_len + end_len))

    return start + padding + end


def __send_card_status_warning(card, status):
    telegram_header = "Exe Card Status Notification"
    notif_message = "The Exe card account Status is not normal."
    message = "Bank: " + (card.bank_en or card.bank) + "\r\n" + \
        " Card Code: " + card.name + "\r\n" + \
        " Username: " + unicode(card.account_holder) + "\r\n" + \
        " Account No: " + card.account_number + "\r\n" + \
        " Message: " + unicode(notif_message) + "\r\n" + \
        " Status: " + unicode(status) + "\r\n"
    message = "*" + telegram_header + "* \r\n``` " + message + " ```"
    send(message, "status.host")
